package com.ambitor.ipro.app.sche;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.BlockingQueue;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ambitor.grass.sql.dao.SuperDao;
import com.ambitor.grass.sql.dao.impl.SuperDaoImpl;
import com.ambitor.grass.util.data.IData;
import com.ambitor.ipro.entities.TradeState;
import com.ambitor.ipro.service.TopService;
import com.ambitor.ipro.util.Constants;
import com.ambitor.ipro.util.LocalConnectionUtils;

public class TaskConsumer implements Runnable {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private BlockingQueue<IData> taskQueue = null;
	private SuperDao superDao = null;
	private TopService topService = null;

	public TaskConsumer(BlockingQueue<IData> taskQueue) {
		this.taskQueue = taskQueue;
		this.topService = new TopService(Constants.EVN_SWITCH,
				Constants.APP_KEY_IPROMOTION, Constants.APP_SECRET_IPROMOTION);
	}

	public void run() {
		while (true) {
			try {
				IData task = taskQueue.take();
				execute(task);
			} catch (InterruptedException e) {
				logger.warn("taskQueue.take()发生异常", e);
				continue;
			}
		}
	}

	private void execute(IData task) {
		Connection conn = this.getConnection();
		if (conn == null)
			return;
		try {
			superDao = new SuperDaoImpl(conn);
			String tradeType = task.getString("TRADE_TYPE");
			String tradeState = task.getString("TRADE_STATE");
			boolean retryFlag = false;
			if (TradeState.UN_EXECUTE_RETRY.equalsIgnoreCase(tradeState)) {
				retryFlag = true;
			}
			if (StringUtils.contains(Constants.INSTALL_TRADE_TYPES, tradeType)) {
				Installer installer = new Installer(superDao, topService);
				installer.setTask(task);
				installer.setTryFlag(retryFlag);
				installer.install();
			} else if (StringUtils.contains(Constants.UNINSTALL_TRADE_TYPES,
					tradeType)) {
				Uninstaller uninstaller = new Uninstaller(superDao, topService);
				uninstaller.setTask(task);
				uninstaller.setTryFlag(retryFlag);
				uninstaller.uninstall();
			} else {
				logger.warn("trade_tyle==" + tradeType + "类型未知");
			}
		} catch (Exception e) {
			logger.error("执行batch_id=" + task.getString("BATCH_ID")
					+ "的工单时发生异常", e);
		} finally {
			try {
				if (conn != null)
					conn.close();
			} catch (SQLException e) {
			}
		}
	}

	private Connection getConnection() {
		Connection conn = null;
		int tryTimes = 0;
		while (tryTimes < Constants.TAOBAO_API_CALL_MAX_TIMES) {
			try {
				conn = LocalConnectionUtils.getConnection();
				break;
			} catch (SQLException e) {
				logger.error("获取Connection出现异常", e);
				tryTimes++;
				sleep(30 * 1000); // 停30秒
			}
		}
		return conn;
	}

	private void sleep(int time) {
		try {
			Thread.sleep(time);
		} catch (InterruptedException exp) {
		}
	}
}
